from flask import Flask, jsonify, request
import BoardBasics
import socket

# 工厂模式 一个非常常用的用于创建对象的设计模式
app = Flask(__name__)


# black or white，value = 1为黑，2为白
class Chessman:
    def __init__(self, name, id, color, IP):
        self.name = name  # black / white
        self.id = id  # 1 / 2  原为 value
        self.color = color  # (219, 219, 219) / (45, 45, 45)
        self.IP = IP
        pass

    pass


# EMPTY_CHESSMAN = Chessman('empty', 0, (128, 128, 128), '0.0.0.0')
# BLACK_CHESSMAN = Chessman('black', 1, (45, 45, 45), '100.21.564.23')
# WHITE_CHESSMAN = Chessman('white', 2, (219, 219, 219), '120.17.585.42')

Chessman_agent = []

# 初始棋盘
boardClass = BoardBasics.Board(BoardBasics.LINES)
board_dict_send = {'board': boardClass.getBoard(),
                   'runner': 'black',
                   'win': 0,
                   'newvalue': 0,  # INIT=0（尚未开始），ACTIVE（已开始）=1，IDLE（空闲）=2，OVER（结束）=3
                   'lastX': -1,
                   'lastY': -1
                   }

board_dict_rec = {'x': -1,
                  'y': -1}

# 测试变量处初值
win = 0
_win_ = 0
newvalue = 0
newID = 1

x = 0
y = 0


@app.route('/')
def index():
    return 'Hello OmegaGo'


# 当前棋局管理
@app.route('/rest/play', methods=['GET'])
def getPlay():
    global win, newvalue, board_dict_send

    if boardClass.winner == BoardBasics.BLACK_CHESSMAN:
        win = 1
    elif boardClass.winner == BoardBasics.WHITE_CHESSMAN:
        win = 2
    else:
        win = 0
        pass

    board_dict_send['board'] = boardClass.getBoard()
    board_dict_send['runner'] = boardClass.cur_runner.name
    board_dict_send['win'] = win
    board_dict_send['newvalue'] = newvalue
    board_dict_send['lastX'] = board_dict_rec['x']
    board_dict_send['lastY'] = board_dict_rec['y']
    return board_dict_send


@app.route('/rest/play/state', methods=['GET'])
def getState():
    global newvalue, board_dict_send
    newvalue = int(request.args.get('newvalue', ''))
    if newvalue == 0:
        return "游戏尚未开始！"
    elif newvalue == 1:
        return "游戏已开始！"
    elif newvalue == 2:
        return "游戏空闲（？？？？？）"
    elif newvalue == 3:
        return "游戏已结束！"
    else:
        return "错误！"


@app.route('/rest/play/report', methods=['GET'])
def getReport():
    global win, board_dict_send, _win_
    _win_ = board_dict_send['win']
    print(_win_)
    if _win_ == 0:
        report = "游戏正在进行，该局游戏为1v1，人机模式"
    elif _win_ == 1:
        report = "游戏结束，胜者为黑子！"
    elif _win_ == 2:
        report = "游戏结束，胜者为白子！"
    else:
        report = "错误！"
    return {'report': report}


# 玩家管理
@app.route('/rest/player', methods=['GET', 'POST'])
def getPlayer():
    global newID
    if request.method == 'GET':
        return 1
        # return {
        #     "black": BLACK_CHESSMAN.IP,
        #     "white": WHITE_CHESSMAN.IP,
        # }
    elif request.method == 'POST':
        name = request.form['color']
        if name == 'black':
            color = BoardBasics.BLACK_STONE_COLOR
        elif name == 'white':
            color = BoardBasics.WHITE_STONE_COLOR
        elif name == 'yellow':
            color = BoardBasics.YELLOW_STONE_COLOR
        else:
            return 'error: color'

        newChessman = Chessman(name, newID, color, request.form['IP'])
        Chessman_agent.append(newChessman)
        newID = newID + 1
        return {
            "succ": '{} joint successfully'.format(name),
            "msg": 'number of players: {}'.format(newID - 1),
            "id": newID - 1
        }


@app.route('/rest/player/<int:id>', methods=['GET'])
def getPlayerMsg(id):
    for Chessman_agent_item in Chessman_agent:
        if Chessman_agent_item.id == id:
            return jsonify({'name': Chessman_agent_item.name,
                            'id': Chessman_agent_item.id,
                            'IP': Chessman_agent_item.IP,
                            'color': Chessman_agent_item.color,
                            })


count = 0


# 当前棋盘管理
@app.route('/rest/board', methods=['GET', 'POST'])
def getBoard():
    global x, y, board_dict_rec, boardClass, count, newvalue
    if request.method == 'GET':
        return {
            "board": boardClass.getBoard(),
            "width": 3,
            "height": 3,
        }
    elif request.method == 'POST':
        new_id = int(request.form['id'])
        new_x = int(request.form['x'])
        new_y = int(request.form['y'])

        board_dict_rec['x'] = new_x
        board_dict_rec['y'] = new_y

        if new_x == -1 or new_y == -1:
            count += 1
            newvalue = 1
            if count == 2:
                boardClass = BoardBasics.Board(BoardBasics.LINES)
                count = 0
                newvalue = 0
                pass

            return 'successfully reset'

        point = BoardBasics.Point(new_x, new_y)
        boardClass.winner = boardClass.drop(boardClass.cur_runner, point)
        if boardClass.winner is not None:
            newvalue = 2
            pass

        boardClass.cur_runner = boardClass.getNextRunner(boardClass.cur_runner)

        return {
            "succ": 'id: {} post successfully'.format(new_id),
            "msg": 'current {}'.format(boardClass.cur_runner.name)
        }


# 走子管理


if __name__ == '__main__':
    app.run(debug=True)
